package com.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bean.ResponseBean;
import com.pojo.Area;
import com.pojo.Zhuji;
import com.service.AppAdminService;
import com.service.AreaService;
import com.service.ZhujiService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 *  非手动断开连接（定时任务）
 */
@Component
public class Zhuji_lianjieDK {

    @Autowired
    private ZhujiService zhujiService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private AreaService areaService;

    /**
     * 每分钟执行一次判断上一次更新的时间
     */
    @Scheduled(cron = "0 * * * * ?")
    public void resetZhuji () throws InterruptedException {
        RLock rLock = redissonClient.getLock("resetZhuji");
        boolean f = rLock.tryLock(0,2000, TimeUnit.MILLISECONDS);
        try {
            if (f) {
                // scan获取需要匹配的key
//                String patternKey = "pay:*";
//                ScanOptions options = ScanOptions.scanOptions()
                        //这里指定每次扫描key的数量(很多博客瞎说要指定Integer.MAX_VALUE，这样的话跟 keys有什么区别？)
//                        .count(10000)
//                        .match(patternKey).build();
//                RedisSerializer<String> redisSerializer = (RedisSerializer<String>) stringRedisTemplate.getKeySerializer();
//                Cursor cursor = (Cursor) stringRedisTemplate.executeWithStickyConnection(redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize));
//                List<String> result = new ArrayList<>();
//                while(cursor.hasNext()){
//                    result.add(cursor.next().toString());
//                }
                //切记这里一定要关闭，否则会耗尽连接数。报Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a
//                cursor.close();
                // keys获取需要匹配的key
                Set<String> keys = stringRedisTemplate.keys("time_"+"*");
                // 批量获取数据
                if (keys.size() > 0) {
                    for (String s : keys) {
                        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(s);
                        if (map != null) {
//                            System.out.println("time：" + map);
                            if(map.get("zhuji_id")==null){
                                stringRedisTemplate.delete(s);
                                return;
                            }
                            Long time = Long.valueOf(map.get("gengxin_time").toString());
                            Long newtime = new Date().getTime();
                            if ((newtime - time) / (1000 * 60) >= 2) {
                                Zhuji zhuji = zhujiService.getById(map.get("zhuji_id").toString());
                                if (zhuji == null) {
                                    stringRedisTemplate.delete(s);
                                    return;
                                }
                                if (zhuji.getSy_lianjie_num() - 1 >= 0) {
                                    zhuji.setSy_lianjie_num(zhuji.getSy_lianjie_num() - 1);
                                    if (zhujiService.updateById(zhuji)) {
                                        QueryWrapper<Zhuji> queryWrapper = new QueryWrapper();
                                        queryWrapper.select("sum(lianjie_num) as lianjie_num,sum(sy_lianjie_num) as sy_lianjie_num");
                                        queryWrapper.eq("area_id", zhuji.getArea_id());
                                        Zhuji zj = zhujiService.getOne(queryWrapper);
                                        if (zj != null && zj.getLianjie_num() > zj.getSy_lianjie_num()) {  //设置地区状态为绿色  未满
                                            Area area = areaService.getById(zhuji.getArea_id());
                                            area.setStatus(0);
                                            areaService.updateById(area);
                                        }
                                        stringRedisTemplate.delete(s);
                                    }
                                }else {
                                    stringRedisTemplate.delete(s);
                                }
                            }
                        }
                    }
                }else {
                    List<Zhuji> list = zhujiService.list();
                    list.stream().forEach(z->{
                        if(!(z.getSy_lianjie_num().equals(0))) {
                            z.setSy_lianjie_num(0);
                            if (zhujiService.updateById(z)) {
                                QueryWrapper<Zhuji> queryWrapper = new QueryWrapper();
                                queryWrapper.select("sum(lianjie_num) as lianjie_num,sum(sy_lianjie_num) as sy_lianjie_num");
                                queryWrapper.eq("area_id", z.getArea_id());
                                Zhuji zj = zhujiService.getOne(queryWrapper);
                                if (zj != null && zj.getLianjie_num() > zj.getSy_lianjie_num()) {  //设置地区状态为绿色  未满
                                    Area area = areaService.getById(z.getArea_id());
                                    area.setStatus(0);
                                    areaService.updateById(area);
                                }
                            }
                        }
                    });
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(rLock.isLocked()) {
                if(rLock.isHeldByCurrentThread()) {
                    rLock.unlock();
                }
            }
        }
    }
}
